package com.czy.owner.ui.work;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.WorkShowAdapter;
import com.czy.owner.api.GoodsDetailApi;
import com.czy.owner.api.GoodsRemainCountApi;
import com.czy.owner.api.MaintenanceDetailsApi;
import com.czy.owner.api.MaintenanceManualDetailApi;
import com.czy.owner.api.MaintenanceWorkDetailApi;
import com.czy.owner.callback.RecyclerHeadersDecoration;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.CarInfo;
import com.czy.owner.entity.DeliveryWayEntity;
import com.czy.owner.entity.DetectionResult;
import com.czy.owner.entity.GoodsDetailModel;
import com.czy.owner.entity.GoodsEntity;
import com.czy.owner.entity.WorkShowEntity;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.archive.MaintenanceManualActivity;
import com.czy.owner.ui.archive.MaintenanceRecordActivity;
import com.czy.owner.ui.physicalorder.ConfirmOrderActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.glide.GlideUtils;
import com.czy.owner.widget.TagsLayout;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

import static com.czy.owner.ui.physicalorder.ConfirmOrderActivity.ConfirmOrderJumpType.WORK;
import static com.czy.owner.ui.physicalorder.ConfirmOrderActivity.TRANSMISSION_CAR_INFO;
import static com.czy.owner.ui.physicalorder.ConfirmOrderActivity.TRANSMISSION_GOODS_TYPE_KEY;

/**
 * Created by King on 2017-05-18
 * 保养检测列表展示
 */

public class WorkShowActivity extends BaseActivity {
    @BindView(R.id.tv_mileage)
    TextView tvMileage;
    @BindView(R.id.tv_manual)
    TextView tvManual;
    @BindView(R.id.tv_record)
    TextView tvRecord;

    @BindView(R.id.rv_work_show)
    RecyclerView rvWorkShow;
    @BindView(R.id.tv_pay_amount)
    TextView tvPayAmount;
    @BindView(R.id.tv_work_pay)
    TextView tvWorkPay;

    private List<WorkShowEntity> workShowData;
    private WorkShowAdapter mAdapter;

    private List<WorkShowEntity> reallyShowData;
    private List<GoodsEntity> orderGoods;
    private WorkJumpType workJumpType;
    private CarInfo mCarInfo;

    private DetectionResult mDetectionResult;
    private String modelsId, manualPointId;

    private double sumGoodsPrice;

    private PopupWindow popWnd;
    private ArrayList<TextView> tvTabs = new ArrayList<>();
    private ArrayList<TextView> tvPostageTabs = new ArrayList<>();


    public static final String TRANSMISSION_WORK_TYPE_KEY = "work_type_key";
    public static final String TRANSMISSION_WORK_EXTEND_KEY = "work_extend_key";
    private static final int SELECT_STORE_TYPE = 0x11;

    public enum WorkJumpType {
        DETECTION,         // 保养检测跳转过来的
        INDEX,              // 首页
        MANUAL              // 保养手册
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_work_show;
    }

    @Override
    protected void initInjector() {
        if (getIntent().getExtras() == null || (mCarInfo = (CarInfo) getIntent().getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY)) == null) {
            PhoneUtils.ShowToastMessage(this, "参数异常!");
            finish();
            return;
        }

        workJumpType = (WorkJumpType) getIntent().getSerializableExtra(TRANSMISSION_WORK_TYPE_KEY);
        switch (workJumpType) {
            case DETECTION:
                mDetectionResult = (DetectionResult) getIntent().getSerializableExtra(TRANSMISSION_WORK_EXTEND_KEY);
                //Toast.makeText(this, mDetectionResult.getMaintenanceManualId() + "|" + mDetectionResult.getTimeMileageId(), Toast.LENGTH_SHORT).show();
                getMaintenanceDetectDetails();
                break;
            case INDEX:
                modelsId = getIntent().getStringExtra(TRANSMISSION_WORK_EXTEND_KEY);
                getMaintenanceWorkDetails();
                break;
            case MANUAL:
                manualPointId = getIntent().getStringExtra(TRANSMISSION_WORK_EXTEND_KEY);
                getMaintenanceManualDetailDetails();
                break;
        }
    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(mCarInfo.getChName());
        tvMileage.setText("" + mCarInfo.getCurrentMileage());
        tvManual.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(WorkShowActivity.this, MaintenanceManualActivity.class).putExtra(Constants.TRANSMISSION_CONTENT_KEY, mCarInfo), 0);
            }
        });

        tvRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(WorkShowActivity.this, MaintenanceRecordActivity.class).putExtra(Constants.TRANSMISSION_CONTENT_KEY, mCarInfo));
            }
        });

        tvWorkPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getGoodsRemainCount(orderGoods);
            }
        });
    }

    @Override
    protected void updateViews() {

    }

    private void showAdapter() {
        mAdapter = new WorkShowAdapter(this, reallyShowData);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        mAdapter.setWorkGroupOperationListener(new WorkShowAdapter.WorkGroupOperationListener<WorkShowEntity>() {
            @Override
            public void onToggleExpanded(int position, WorkShowEntity o, View view) {
                WorkShowEntity.SonModelsBean workGroup = (WorkShowEntity.SonModelsBean) o.getShowData();
                a:
                for (int i = 0; i < workShowData.size(); i++) {
                    for (int j = 0; j < workShowData.get(i).getSonModels().size(); j++) {
                        if (workShowData.get(i).getModelsId() == o.getModelsId() && workShowData.get(i).getSonModels().get(j).getModelsId() == workGroup.getModelsId()) {
                            workShowData.get(i).getSonModels().get(j).setExpanded(!workShowData.get(i).getSonModels().get(j).isExpanded());
                            break a;
                        }
                    }
                }
                generateShowData();
                mAdapter.setList(reallyShowData);


            }

            @Override
            public void onChecked(int position, WorkShowEntity o, View view) {
                WorkShowEntity.SonModelsBean workGroup = (WorkShowEntity.SonModelsBean) o.getShowData();
                a:
                for (int i = 0; i < workShowData.size(); i++) {
                    for (int j = 0; j < workShowData.get(i).getSonModels().size(); j++) {
                        if (workShowData.get(i).getModelsId() == o.getModelsId() && workShowData.get(i).getSonModels().get(j).getModelsId() == workGroup.getModelsId()) {
                            workShowData.get(i).getSonModels().get(j).setPicked(!workShowData.get(i).getSonModels().get(j).isPicked());
                            if (workShowData.get(i).getSonModels().get(j).isPicked()) {
                                workShowData.get(i).getSonModels().get(j).setExpanded(true);
                            }
                            break a;
                        }
                    }
                }
                generateShowData();
                mAdapter.setList(reallyShowData);

                calculatePickedGoods();
            }

            @Override
            public void onSpec(int position, WorkShowEntity workShowEntity, final View view) {
                final GoodsEntity mGoodEntity = (GoodsEntity) workShowEntity.getShowData();
                GoodsDetailApi goodsDetailApi = new GoodsDetailApi(new HttpOnNextListener<GoodsDetailModel>() {
                    @Override
                    public void onNext(GoodsDetailModel model) {
                        initPopWindow(mGoodEntity, model, view);
                    }


                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        PhoneUtils.ShowToastMessage(WorkShowActivity.this, e.getMessage());
                    }
                }, WorkShowActivity.this);
                goodsDetailApi.setSession(UserHelper.getInstance().getSessionInfoModel(WorkShowActivity.this).getSession());
                goodsDetailApi.setGoodsId(mGoodEntity.getGoodsId() + "");
                HttpManager manager = HttpManager.getInstance();
                manager.doHttpDeal(goodsDetailApi);
            }
        });
        rvWorkShow.setLayoutManager(layoutManager);
        rvWorkShow.setAdapter(mAdapter);
        final RecyclerHeadersDecoration headersDecor = new RecyclerHeadersDecoration(mAdapter);
        rvWorkShow.addItemDecoration(headersDecor);

        //   setTouchHelper();
        mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                headersDecor.invalidateHeaders();
            }
        });
        mAdapter.notifyDataSetChanged();
    }

    private void getMaintenanceDetectDetails() {
        MaintenanceDetailsApi mApi = new MaintenanceDetailsApi(new HttpOnNextListener<List<WorkShowEntity>>() {
            @Override
            public void onNext(List<WorkShowEntity> o) {
                workShowData = o;
                generateShowData();
                showAdapter();
            }
        }, this);

        HashMap<String, Object> requestMap = new HashMap<>();
        requestMap.put("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        requestMap.put("maintenanceManualId", mDetectionResult.getMaintenanceManualId());
        requestMap.put("timeMileageId", mDetectionResult.getTimeMileageId());
        requestMap.put("carBrandId", mCarInfo.getCarBrandId());
        mApi.setMap(requestMap);
        HttpManager.getInstance().doHttpDeal(mApi);
    }

    private void getMaintenanceWorkDetails() {
        MaintenanceWorkDetailApi mApi = new MaintenanceWorkDetailApi(new HttpOnNextListener<WorkShowEntity>() {
            @Override
            public void onNext(WorkShowEntity o) {
                workShowData = new ArrayList<>();
                workShowData.add(o);
                generateShowData();
                showAdapter();
            }
        }, this);

        HashMap<String, Object> requestMap = new HashMap<>();
        requestMap.put("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        requestMap.put("carBrandId", mCarInfo.getCarBrandId());
        requestMap.put("mileage", mCarInfo.getCurrentMileage());
        requestMap.put("modelsId", modelsId);
        mApi.setMap(requestMap);
        HttpManager.getInstance().doHttpDeal(mApi);
    }

    private void getMaintenanceManualDetailDetails() {
        MaintenanceManualDetailApi mApi = new MaintenanceManualDetailApi(new HttpOnNextListener<WorkShowEntity>() {
            @Override
            public void onNext(WorkShowEntity o) {
                workShowData = new ArrayList<>();
                workShowData.add(o);
                generateShowData();
                showAdapter();
            }
        }, this);

        HashMap<String, Object> requestMap = new HashMap<>();
        requestMap.put("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        requestMap.put("manualPointId", manualPointId);
        requestMap.put("carBrandId", mCarInfo.getCarBrandId());
        mApi.setMap(requestMap);
        HttpManager.getInstance().doHttpDeal(mApi);
    }

    private void generateShowData() {
        reallyShowData = new ArrayList<>();
        for (int i = 0; i < workShowData.size(); i++) {
            for (int j = 0; j < workShowData.get(i).getSonModels().size(); j++) {
                WorkShowEntity workShowEntity = new WorkShowEntity();
                workShowEntity.setModelsId(workShowData.get(i).getModelsId());
                workShowEntity.setModelsName(workShowData.get(i).getModelsName());
                workShowEntity.setShowDataType(0);
                workShowEntity.setShowData(workShowData.get(i).getSonModels().get(j));
                reallyShowData.add(workShowEntity);
                if (workShowData.get(i).getSonModels().get(j).isExpanded()) {
                    for (int k = 0; k < workShowData.get(i).getSonModels().get(j).getGoods().size(); k++) {
                        if(workShowData.get(i).getSonModels().get(j).getGoods().get(k) != null){
                            WorkShowEntity workShowDetail = new WorkShowEntity();
                            workShowDetail.setModelsId(workShowData.get(i).getModelsId());
                            workShowDetail.setModelsName(workShowData.get(i).getModelsName());
                            workShowDetail.setShowDataType(1);
                            workShowData.get(i).getSonModels().get(j).getGoods().get(k).setNeedInstall(true);
                            workShowDetail.setShowData(workShowData.get(i).getSonModels().get(j).getGoods().get(k));
                            reallyShowData.add(workShowDetail);
                        }
                    }
                }
            }
        }


    }

    private void calculatePickedGoods() {
        sumGoodsPrice = 0;
        orderGoods = new ArrayList<>();
        for (int i = 0; i < workShowData.size(); i++) {
            for (int j = 0; j < workShowData.get(i).getSonModels().size(); j++) {
                if (workShowData.get(i).getSonModels().get(j).isPicked()) {
                    for (int k = 0; k < workShowData.get(i).getSonModels().get(j).getGoods().size(); k++) {
                        if(workShowData.get(i).getSonModels().get(j).getGoods().get(k) != null){
                            sumGoodsPrice += workShowData.get(i).getSonModels().get(j).getGoods().get(k).getCount()  * workShowData.get(i).getSonModels().get(j).getGoods().get(k).getGoodsSpecValuesPrice();
                            // TODO  默认全部需要安装
                            workShowData.get(i).getSonModels().get(j).getGoods().get(k).setInstall(true);
                            workShowData.get(i).getSonModels().get(j).getGoods().get(k).setNeedInstall(true);

                            orderGoods.add(workShowData.get(i).getSonModels().get(j).getGoods().get(k));
                        }
                    }
                }
            }
        }
        DecimalFormat decimalFormat = new DecimalFormat("0.##");
        tvPayAmount.setText("￥" + decimalFormat.format(sumGoodsPrice));
        if (sumGoodsPrice == 0) {
            tvWorkPay.setBackgroundColor(Color.parseColor("#CCCCCC"));
            tvWorkPay.setEnabled(false);
        } else {
            tvWorkPay.setBackgroundResource(R.color.appThemeColor);
            tvWorkPay.setEnabled(true);
        }
    }


    private void initPopWindow(final GoodsEntity mGoodEntity, final GoodsDetailModel goodsDetailModel, View v) {
        /*specList = model.getSelectedSpecList();
        specGroupList = model.getGoodsList();
        selectPostageId = 0;
        serviceInstallStoreId = 0;

        selectSpecValueListBean.clear();*/
        tvPostageTabs.clear();

        tvTabs.clear();
        if (goodsDetailModel != null) {
            View contentView = LayoutInflater.from(WorkShowActivity.this).inflate(R.layout.pop_goods_standard, null);
            popWnd = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            if (popWnd != null) {
                contentView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popWnd.dismiss();
                    }
                });
            }
            LinearLayout llPopTop = (LinearLayout) contentView.findViewById(R.id.pop_top);
            llPopTop.setOnTouchListener(new View.OnTouchListener() {                                //拦截点击事件
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return true;
                }
            });
            ColorDrawable cd = new ColorDrawable(0x77000000);
            popWnd.setBackgroundDrawable(cd);
            // 设置点击窗口外边窗口消失
            popWnd.setOutsideTouchable(true);
            // 设置此参数获得焦点，否则无法点击
            popWnd.setFocusable(true);
            popWnd.setAnimationStyle(R.style.ShoppingCartPopupAnimation);
            popWnd.setClippingEnabled(true);
            LinearLayout llContainer = (LinearLayout) contentView.findViewById(R.id.ll_container);
            final TextView tvSure = (TextView) contentView.findViewById(R.id.tv_sure);
            final TextView tvPopChooseSpec = (TextView) contentView.findViewById(R.id.tv_pop_choose_spec);
            final TextView tvGoodsPrice = (TextView) contentView.findViewById(R.id.tv_goods_price);
            final ImageView ivPopGoodsDetail = (ImageView) contentView.findViewById(R.id.iv_pop_goods_detail);
            ImageView ivGoodsMinus = (ImageView) contentView.findViewById(R.id.iv_goods_minus);
            final TextView tvGoodsCount = (TextView) contentView.findViewById(R.id.tv_goods_count);
            ImageView ivGoodsAdd = (ImageView) contentView.findViewById(R.id.iv_goods_add);
            GlideUtils.loadImage(this, goodsDetailModel.getGoodsLogo(), ivPopGoodsDetail, null, R.mipmap.icon_goods_list_default, R.mipmap.icon_goods_list_default);
            if (goodsDetailModel.getSpecList().size() == 0) {
                tvPopChooseSpec.setText("无规格");
                tvGoodsPrice.setText("￥" + goodsDetailModel.getPrice());
            }
            GoodsDetailModel.SpecGroupListBean pickedSpecGroup = null;
            if (!TextUtils.isEmpty(mGoodEntity.getSpecGroupKey())) {
                for (int i = 0; i < goodsDetailModel.getSpecGroupList().size(); i++) {
                    if (mGoodEntity.getSpecGroupKey().equals(goodsDetailModel.getSpecGroupList().get(i).getSpecGroupKey())) {
                        pickedSpecGroup = goodsDetailModel.getSpecGroupList().get(i);
                        break;
                    }
                }
            }
            StringBuilder specSB = new StringBuilder();

            for (int i = 0; i < goodsDetailModel.getSpecList().size(); i++) {
                View addView = LayoutInflater.from(WorkShowActivity.this).inflate(R.layout.include_goods_standard, null);
                TagsLayout tagsClassify = (TagsLayout) addView.findViewById(R.id.tags_classify);
                TextView tvClassifyName = (TextView) addView.findViewById(R.id.tv_classify_name);
                ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                tvClassifyName.setText(goodsDetailModel.getSpecList().get(i).getSpecName());
                for (int j = 0; j < goodsDetailModel.getSpecList().get(i).getSpecValueList().size(); j++) {
                    View tagView = View.inflate(WorkShowActivity.this, R.layout.item_screen_brand, null);
                    TextView textView = (TextView) tagView.findViewById(R.id.tv_screen_item);
                    GoodsDetailModel.SpecListBean.SpecValueListBean tag = goodsDetailModel.getSpecList().get(i).getSpecValueList().get(j);
                    textView.setText(tag.getSpecValue());
                    textView.setTag(tag);
                    if (pickedSpecGroup != null && pickedSpecGroup.getIdGroup().contains(tag.getSpecId() + ":" + tag.getSpecValuesId()) && pickedSpecGroup.getGoodsSpecId().contains(tag.getSpecId() + ":" + tag.getSpecValue())) {
                        Log.i("King ", pickedSpecGroup.getIdGroup() + "|" + (tag.getSpecId() + ":" + tag.getSpecValuesId()));
                        textView.setTextColor(getResources().getColor(R.color.appThemeColor));
                        textView.setBackgroundResource(R.drawable.shape_app_theme_frame);
                        textView.setSelected(true);
                        if (j == goodsDetailModel.getSpecList().get(i).getSpecValueList().size() - 1) {
                            specSB.append(tag.getSpecValue());
                        } else {
                            specSB.append(tag.getSpecValue() + ",");
                        }
                    }
                    tvTabs.add(textView);
                    tagView.setTag(false);
                    tagView.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            TextView tv = (TextView) v.findViewById(R.id.tv_screen_item);
                            updateSelectTabs(mGoodEntity, goodsDetailModel, tv, tvGoodsPrice, tvPopChooseSpec, ivPopGoodsDetail);
                        }
                    });
                    tagsClassify.addView(tagView, lp);
                }

                llContainer.addView(addView);
            }
            if (pickedSpecGroup != null && goodsDetailModel.getSpecList().size() > 0) {
                tvGoodsPrice.setText("￥" + pickedSpecGroup.getGoodsSpecValuesPrice());
                tvPopChooseSpec.setText("已选择" + specSB);
            }
            mGoodEntity.setInstall(true);   //goodsDetailModel.isInstall()
            mGoodEntity.setPostageFree(goodsDetailModel.isPostageFree());

            if (!goodsDetailModel.isPostageFree()) {
                List<DeliveryWayEntity> deliveryWayList = goodsDetailModel.getDeliveryWayList();
                View addView = LayoutInflater.from(WorkShowActivity.this).inflate(R.layout.include_goods_standard, null);
                TagsLayout tagsClassify = (TagsLayout) addView.findViewById(R.id.tags_classify);
                TextView tvClassifyName = (TextView) addView.findViewById(R.id.tv_classify_name);
                ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                tvClassifyName.setText("配送方式");
                for (int j = 0; j < deliveryWayList.size(); j++) {
                    View tagView = View.inflate(WorkShowActivity.this, R.layout.item_screen_brand, null);
                    TextView textView = (TextView) tagView.findViewById(R.id.tv_screen_item);
                    DeliveryWayEntity deliveryWayListBean = deliveryWayList.get(j);
                    textView.setText(deliveryWayListBean.getName());
                    textView.setTag(deliveryWayListBean);
                    if (mGoodEntity.getDeliveryWay() != null && mGoodEntity.getDeliveryWay().getDeliveryWayId() == deliveryWayListBean.getDeliveryWayId()) {
                        textView.setTextColor(getResources().getColor(R.color.appThemeColor));
                        textView.setBackgroundResource(R.drawable.shape_app_theme_frame);
                    }
                    tvPostageTabs.add(textView);
                    tagView.setTag(false);
                    tagView.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            // TODO 点击时更新物流按钮状态
                            TextView tv = (TextView) v.findViewById(R.id.tv_screen_item);
                            updatePostageView(mGoodEntity, tv);
                        }
                    });
                    tagsClassify.addView(tagView, lp);
                }
                llContainer.addView(addView);
            }

            ivGoodsMinus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mGoodEntity.getCount() > 1) {
                        mGoodEntity.setCount(mGoodEntity.getCount() - 1);
                        tvGoodsCount.setText(mGoodEntity.getCount() + "");
                    } else {
                        mGoodEntity.setCount(1);
                    }
                    mAdapter.notifyDataSetChanged();
                    calculatePickedGoods();
                }
            });
            ivGoodsAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mGoodEntity.getCount() < 1) {
                        mGoodEntity.setCount(1);
                    }
                    mGoodEntity.setCount(mGoodEntity.getCount() + 1);
                    tvGoodsCount.setText(mGoodEntity.getCount() + "");
                    mAdapter.notifyDataSetChanged();
                    calculatePickedGoods();
                }
            });
            tvSure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //AddToCartRequest(model);
                    popWnd.dismiss();

                }
            });
            //initPopTabs(tvGoodsPrice, tvPopChooseSpec, tvGoodsCount);
            if (mGoodEntity.getCount() < 1) {
                mGoodEntity.setCount(1);
            }
            tvGoodsCount.setText("" + mGoodEntity.getCount());
            popWnd.showAtLocation(v, Gravity.BOTTOM, 0, 0);

        }
    }

    private void updateSelectTabs(GoodsEntity mGoodsEntity, GoodsDetailModel goodsDetailModel, TextView tv, TextView tvGoodsPrice, TextView tvPopChooseSpec, ImageView ivPopGoodsDetail) {
        GoodsDetailModel.SpecListBean.SpecValueListBean tag = (GoodsDetailModel.SpecListBean.SpecValueListBean) tv.getTag();
        int tagSpecId = tag.getSpecId();
        int tagSpecValuesId = tag.getSpecValuesId();
        for (int i = 0; i < tvTabs.size(); i++) {
            GoodsDetailModel.SpecListBean.SpecValueListBean tabsTag = (GoodsDetailModel.SpecListBean.SpecValueListBean) tvTabs.get(i).getTag();
            if (tabsTag.getSpecId() == tagSpecId) {
                if (tagSpecValuesId == tabsTag.getSpecValuesId()) {
                    tvTabs.get(i).setTextColor(getResources().getColor(R.color.appThemeColor));
                    tvTabs.get(i).setBackgroundResource(R.drawable.shape_app_theme_frame);
                    tvTabs.get(i).setSelected(true);
                } else {
                    tvTabs.get(i).setTextColor(getResources().getColor(R.color.appThemeSubTitleColor));
                    tvTabs.get(i).setBackgroundResource(R.drawable.shape_gray_frame);
                    tvTabs.get(i).setSelected(false);
                }
            }
        }
        //1:15,2:16
        StringBuilder idGroup = new StringBuilder();
        StringBuilder specSB = new StringBuilder();
        for (int i = 0; i < tvTabs.size(); i++) {
            if (tvTabs.get(i).isSelected()) {
                GoodsDetailModel.SpecListBean.SpecValueListBean specValueListBean = (GoodsDetailModel.SpecListBean.SpecValueListBean) tvTabs.get(i).getTag();
                if (TextUtils.isEmpty(idGroup)) {
                    idGroup.append(specValueListBean.getSpecId() + ":" + specValueListBean.getSpecValuesId());
                    specSB.append(specValueListBean.getSpecValue());
                } else {
                    idGroup.append("," + specValueListBean.getSpecId() + ":" + specValueListBean.getSpecValuesId());
                    specSB.append("," + specValueListBean.getSpecValue());
                }
            }
        }
        for (int i = 0; i < goodsDetailModel.getSpecGroupList().size(); i++) {
            if (idGroup.toString().equals(goodsDetailModel.getSpecGroupList().get(i).getIdGroup())) {
                mGoodsEntity.setSpecGroupKey(goodsDetailModel.getSpecGroupList().get(i).getSpecGroupKey());
                mGoodsEntity.setGoodsSpecValuesPrice(goodsDetailModel.getSpecGroupList().get(i).getGoodsSpecValuesPrice());
                mGoodsEntity.setToStorePrice(goodsDetailModel.getSpecGroupList().get(i).getToStorePrice());
                mGoodsEntity.setGoodsSpecValuesId(goodsDetailModel.getSpecGroupList().get(i).getGoodsSpecValuesId());
                if (TextUtils.isEmpty(goodsDetailModel.getSpecGroupList().get(i).getLogo())) {
                    GlideUtils.loadImage(this, goodsDetailModel.getGoodsLogo(), ivPopGoodsDetail, null, R.mipmap.icon_goods_list_default, R.mipmap.icon_goods_list_default);
                } else {
                    GlideUtils.loadImage(this, goodsDetailModel.getSpecGroupList().get(i).getLogo(), ivPopGoodsDetail, null, R.mipmap.icon_goods_list_default, R.mipmap.icon_goods_list_default);
                }
                break;
            }
        }
        tvPopChooseSpec.setText("已选择" + specSB);
        tvGoodsPrice.setText("￥" + mGoodsEntity.getGoodsSpecValuesPrice());

        mAdapter.notifyDataSetChanged();
        calculatePickedGoods();



        /*if (selectSpecValueListBean.size() > 0) {
            for (int i = 0; i < specGroupList.size(); i++) {
                if (specGroupList.get(i).getIdGroup().equals((keyGroup + ""))) {
                    tvGoodsPrice.setText("￥" + specGroupList.get(i).getGoodsSpecValuesPrice());
                }

            }


        } else {
            if (specGroupList.size() > 0)
                tvGoodsPrice.setText("￥" + specGroupList.get(0).getGoodsSpecValuesPrice());
        }*/


    }

    private void updatePostageView(GoodsEntity mGoodsEntity, TextView tv) {
        mGoodsEntity.setDeliveryWay((DeliveryWayEntity) tv.getTag());
        for (int i = 0; i < tvPostageTabs.size(); i++) {
            DeliveryWayEntity tag = (DeliveryWayEntity) tvPostageTabs.get(i).getTag();
            if (tag.getDeliveryWayId() == mGoodsEntity.getDeliveryWay().getDeliveryWayId()) {
                tvPostageTabs.get(i).setTextColor(getResources().getColor(R.color.appThemeColor));
                tvPostageTabs.get(i).setBackgroundResource(R.drawable.shape_app_theme_frame);
            } else {
                tvPostageTabs.get(i).setTextColor(getResources().getColor(R.color.appThemeSubTitleColor));
                tvPostageTabs.get(i).setBackgroundResource(R.drawable.shape_gray_frame);
            }
        }

    }


    public void getGoodsRemainCount(final List<GoodsEntity> list) {
        GoodsRemainCountApi goodsRemainCountApi = new GoodsRemainCountApi(new HttpOnNextListener<String>() {
            @Override
            public void onNext(String s) {
                MyLog.e("yang","s=="+s);
                if(popWnd != null){
                    popWnd.dismiss();
                }
                for (int i=0;i<list.size();i++){
                    list.get(i).setFromType(Constants.MAINTENANCE_TESTING);
                    list.get(i).setFromTypeId("0");
                }
                Intent intent = new Intent(WorkShowActivity.this, ConfirmOrderActivity.class);
                intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, (Serializable) list);
                intent.putExtra(TRANSMISSION_GOODS_TYPE_KEY, WORK);
                intent.putExtra(TRANSMISSION_CAR_INFO, mCarInfo);
                intent.putExtra("isShoppingCar","2");
                startActivityForResult(intent,0);
            }


            @Override
            public void onError(Throwable e) {
                super.onError(e);
                e.printStackTrace();
                PhoneUtils.ShowToastMessage(WorkShowActivity.this, e.getMessage());
            }
        }, this);
        goodsRemainCountApi.setSession(UserHelper.getInstance().getSessionInfoModel(this).getSession());
        StringBuilder goodsIds = new StringBuilder();
        StringBuilder specKeys = new StringBuilder();
        StringBuilder numbers = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            goodsIds.append((TextUtils.isEmpty(goodsIds) ? "" : ",") + list.get(i).getGoodsId());
            specKeys.append((TextUtils.isEmpty(specKeys) ? "" : ",") + list.get(i).getSpecGroupKey());
            numbers.append((TextUtils.isEmpty(numbers) ? "" : ",") + list.get(i).getCount());
        }

        goodsRemainCountApi.setGoodsIds(goodsIds + "");
        goodsRemainCountApi.setSpecGroupKeys(specKeys + "");
        goodsRemainCountApi.setNumbers(numbers + "");
        goodsRemainCountApi.setOwnerCarId(mCarInfo.getOwnerCarId()+"");
        HttpManager manager = HttpManager.getInstance();
        manager.doHttpDeal(goodsRemainCountApi);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }
}
